package com.example.timeskilltest.service.impl;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;
import java.util.concurrent.locks.Lock;

import javax.annotation.Resource;

import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.timeskilltest.model.Goods;
import com.example.timeskilltest.model.Orders;
import com.example.timeskilltest.service.GoodsService;
import com.example.timeskilltest.service.OrdersService;
import com.example.timeskilltest.service.TimeSkillService;
import com.example.timeskilltest.util.RedisUtil;

@Service
public class TimeSkillServiceImpl implements TimeSkillService {

    private static final String STOCK_KEY = "timeSkill:stock:";
    @Autowired
    private GoodsService        goodsService;
    @Autowired
    private OrdersService       ordersService;
    @Autowired
    private RedisUtil           redisUtil;
    @Resource
    private RedissonClient      redissonClient;

    @Override
    public void init() {

        List<Goods> list = goodsService.list();

        for (Goods item : list) {
            // 获取或创建一个原子长整型对象
            RAtomicLong atomicLong = redissonClient.getAtomicLong(STOCK_KEY + item.getId());
            // 设置数字
            atomicLong.set(item.getStock());
        }

    }

    @Override
    public String go() {

        // 商品
        int goodsId = 1 + new Random().nextInt(3);

        // 数量
        //        int amount = 1 + new Random().nextInt(1);
        int amount = 1;

        String key = "timeskill:" + goodsId;

        Lock lock = redissonClient.getLock(key);

        String result;

        try {
            // 上锁
            lock.lock();

            // 查库存 => 改成 redis 更快
            RAtomicLong atomicLong = redissonClient.getAtomicLong(STOCK_KEY + goodsId);
            long currStock = atomicLong.get();

            // 有库存
            if (currStock >= amount) {

                // 减库存 => 改成 redis 更快
                atomicLong.getAndAdd(-amount);

                // 插记录 => 异步
                Orders orders = new Orders() //
                    .setGoodsId(goodsId) //
                    .setAmount(1) //
                    .setCreateTime(LocalDateTime.now()) //
                ;
                ordersService.saveTimeskillOrder(orders);

                result = "下单成功!";

            } else {
                result = "没了 " + redisUtil.get(key);
            }

        } finally {
            // 释放锁
            lock.unlock();
        }

        return result;

    }

}
